﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace Sidvall.Tasks
{
    public sealed class DelayTask : MonitoredTaskBase, System.IProgress<long>
    {
        #region Public Members

        #region ExecuteAsync

        public override async Task ExecuteAsync(IProgress<MonitoredTaskProgress> progress, CancellationToken cancellationToken)
        {
            this.Progress = progress;
            for (int i = 0; i < 10; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Task.Delay((int)(TotalWork / 10));
                if (progress != null)
                {
                    Report(TotalWork * (i + 1) / 10);
                }
            }
        }

        #endregion
        #region IProgress members

        public void Report(long value)
        {
            var context = new Sidvall.Tasks.MonitoredTaskProgress()
            {
                TaskId = this.TaskId,
                Description = "Delaying...",
                TotalWork = this.TotalWork,
                CompletedWork = value,
            };
            this.Progress.Report(context);
        }

        #endregion

        #endregion
        #region Private Members

        private System.IProgress<Sidvall.Tasks.MonitoredTaskProgress> Progress { get; set; }
        private long TotalWork { get; set; }

        #endregion
        #region Constructor

        public DelayTask(long totalWork)
        {
            this.TotalWork = totalWork;
        }
        public DelayTask(long totalWork, string taskId)
            : this(totalWork)
        {
            this.TaskId = taskId;
        }

        #endregion
    }
}
